package com.web.exiaodao.remote.controller;

import com.google.common.collect.Lists;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.FranchiseTable;
import com.web.exiaodao.remote.service.ApiFranchiseTableService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.FranchiseAgreementVo;
import com.web.exiaodao.remote.vo.FranchiseTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.ReflectionUtils;
import com.web.webstart.base.util.Validator;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiFranchiseTableController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 加盟申请信息接口
 * @date 2015年3月23日 下午1:00:00
 */
@Api(value = "FranchiseTable", description = "加盟申请接口", position = 10)
@Controller
@RequestMapping("/api/franchiseTable")
public class ApiFranchiseTableController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiFranchiseTableController.class);

    @Autowired
    private ApiFranchiseTableService franchiseTableService;

    @Autowired
    private ApiUserService userService;

    /**
     * @return
     * @Title: findFranchise
     * @Description: 根据ID查找单条实体
     */
    @ApiOperation(value = "加盟申请详情", notes = "查询加盟申请详细信息,当返回的code=1时，取出object进行显示,存放为单体对象")
    @ResponseBody
    @RequestMapping(value = "findFranchise", method = RequestMethod.POST)
    public XaResult<FranchiseTableVo> findFranchise(
            @ApiParam("申请人ID,字段名:userId") @RequestParam(value = "userId") Long userId
    ) throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户id不能为空");
            return xr;
        }
        //用户要存在
        userService.findOne(userId);

        return franchiseTableService.findFranchiseInfo(userId);
    }

    /**
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "加盟申请", notes = "新增加盟申请,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "saveFranchise", method = RequestMethod.POST)
    public XaResult<FranchiseTableVo> saveFranchise(
            @ApiParam("申请人ID,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("申请人姓名,字段名:customer_Name") @RequestParam(value = "customer_Name") String customer_Name,
            @ApiParam("手机号码,字段名:cellphone") @RequestParam(value = "cellphone") String cellphone,
            @ApiParam("公司名称(别的信息全在照片上面),字段名:franchise_Unit_Name") @RequestParam(value = "franchise_Unit_Name") String franchise_Unit_Name,
            @ApiParam("照片多张,用逗号分割,字段名:franchise_Unit_PicUrls") @RequestParam(value = "franchise_Unit_PicUrls") String franchise_Unit_PicUrls,
            @ApiParam("加盟协议代码多个,用逗号分割,字段名:agreements") @RequestParam(value = "agreements") String agreements,
            HttpServletRequest request
    ) throws Exception {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户id不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(customer_Name)) {
            xr.error("申请人姓名不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(cellphone)) {
            xr.error("手机号不能为空");
            return xr;
        }
        if (!Validator.isMobile(cellphone)) {
            xr.error("手机号码格式不正确");
            return xr;
        }
        if (XaUtil.isEmpty(franchise_Unit_Name)) {
            xr.error("公司名称不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(franchise_Unit_PicUrls)) {
            xr.error("图片不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(agreements)) {
            xr.error("加盟协议必选");
            return xr;
        }
        if (!FranchiseAgreementVo.isContainKey(Lists.newArrayList(XaUtil.splitLong(agreements, JConstant.SYMBOL_DOT)))) {
            xr.error("加盟协议不存在!");
            return xr;
        }
        //用户要存在
        userService.findOne(userId);

        //一个人只能申请一次
        Pageable pageable = WebUitl.buildPageRequest(0, 1, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{'search_EQ_userId':'" + userId + "'}", "search_");
        XaResult<List<FranchiseTableVo>> listXaResult = franchiseTableService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
        if (listXaResult != null && listXaResult.getObject().size() >= 1 && listXaResult.getObject().get(0).getFranchise_State() != JConstant.FrancehiseStatus.WAITING.longValue()) {
            if (listXaResult.getObject().get(0).getFranchise_State() == JConstant.FrancehiseStatus.PASS.longValue()) {
                xr.error("您已经申请通过了,请联系管理员");
                LOGGER.error(XaConstant.Message.error, null);
                return xr;
            } else if (listXaResult.getObject().get(0).getFranchise_State() == JConstant.FrancehiseStatus.REFUSE.longValue()) {
                xr.error("您的审核被拒绝,请重提交信息!");
                LOGGER.error(XaConstant.Message.error, null);
                return xr;
            }
        }

        FranchiseTable model = new FranchiseTable();
        model.setUserId(userId);
        model.setCustomer_Name(customer_Name);
        model.setCellphone(cellphone);
        model.setFranchise_Unit_Name(franchise_Unit_Name);
        model.setFranchise_Unit_PicUrls(franchise_Unit_PicUrls);
        model.setFranchise_State(JConstant.FrancehiseStatus.WAITING);
        model.setAgreements(agreements);
        return franchiseTableService.createModel(model);
    }

    /**
     * @return
     * @Title:
     * @Description: 修改一条实体
     */
    @ApiOperation(value = "重新申请加盟", notes = "重新申请加盟,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "updateFranchise", method = RequestMethod.POST)
    public XaResult<FranchiseTableVo> updateFranchise(
            @ApiParam("加盟申请id,字段名:id") @RequestParam(value = "tId") Long tId,
            @ApiParam("申请人姓名,字段名:customer_Name") @RequestParam(value = "customer_Name") String customer_Name,
            @ApiParam("手机号码,字段名:cellphone") @RequestParam(value = "cellphone") String cellphone,
            @ApiParam("公司名称(别的信息全在照片上面),字段名:franchise_Unit_Name") @RequestParam(value = "franchise_Unit_Name") String franchise_Unit_Name,
            @ApiParam("照片（单张）,字段名:franchise_Unit_PicUrls") @RequestParam(value = "franchise_Unit_PicUrls") String franchise_Unit_PicUrls,
            @ApiParam("加盟协议代码多个,用逗号分割,字段名:agreements") @RequestParam(value = "agreements") String agreements,
            HttpServletRequest request
    ) throws Exception {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        if (XaUtil.isEmpty(customer_Name)) {
            xr.error("申请人姓名不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(cellphone)) {
            xr.error("手机号不能为空");
            return xr;
        }
        if (!Validator.isMobile(cellphone)) {
            xr.error("手机号码格式不正确");
            return xr;
        }
        if (XaUtil.isEmpty(franchise_Unit_Name)) {
            xr.error("公司名称不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(agreements)) {
            xr.error("加盟协议必选");
            return xr;
        }
        if (!FranchiseAgreementVo.isContainKey(Lists.newArrayList(XaUtil.splitLong(agreements, JConstant.SYMBOL_DOT)))) {
            xr.error("加盟协议不存在!");
            return xr;
        }

        int length = ReflectionUtils.getHibernateColumnAnnotationLength(FranchiseTable.class, "franchise_Unit_Name");
        if (franchise_Unit_Name.length() > length) {
            xr.error("评论内容不能超过" + length);
            return xr;
        }
        if (XaUtil.isEmpty(franchise_Unit_PicUrls)) {
            xr.error("图片不能为空");
            return xr;
        }

        FranchiseTable model = new FranchiseTable();
        model.setCustomer_Name(customer_Name);
        model.setCellphone(cellphone);
        model.setFranchise_Unit_Name(franchise_Unit_Name);
        model.setFranchise_Unit_PicUrls(franchise_Unit_PicUrls);
        model.setAgreements(agreements);
        model.setId(tId);
        model.setFranchise_State(JConstant.FrancehiseStatus.WAITING);
        return franchiseTableService.updateModel(model);
    }
}

